﻿using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using OnlineStore.Models;
using OnlineStore.Services;
using OnlineStore.Services.Support;
using OnlineStore.Web.Models.User;

namespace OnlineStore.Web.Controllers
{
    public class UserController : Controller
    {
        private readonly IAccountService _accountService;
        private readonly IProductService _productService;


        public UserController(IAccountService accountService, IProductService productService)
        {
            _accountService = accountService;
            _productService = productService;
        }

        // GET
        /// <summary>
        /// 用户主页
        /// 跳转到用户主页
        /// </summary>
        [Authorize]
        public IActionResult Index(int userId)
        {
            return View();
        }


        /// <summary>
        /// 跳转到登入页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Login()
        {
            var loginVm = new LoginViewModel();
            return View(loginVm);
        }

        /// <summary>
        /// 用于登入页面的提交操作
        /// </summary>
        /// <param name="model">Login page Model</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var user = new User
            {
                Email = model.Emails,
                Password = model.Password
            };

            try
            {
                var claimsPrincipal = await _accountService.UserLoginAsync(user);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
            }
            catch (EmailNotFoundException)
            {
                ModelState.AddModelError("", "邮箱不存在!");
                return View(model);
            }

            return RedirectToAction(nameof(Index), "Home");
        }

        /// <summary>
        /// 跳转到注册页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Register()
        {
            var registerVm = new RegisterViewModel();
            return View(registerVm);
        }

        /// <summary>
        /// 用户注册页面的提交操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns>默认跳转到登录页面</returns>
        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var reg = new User
            {
                Email = model.Email,
                Name = model.Name,
                Password = model.Password
            };

            try
            {
                await _accountService.UserRegister(reg);
            }
            catch (EmailNotFoundException)
            {
                ModelState.AddModelError("", "邮箱不存在!");
                return View(model);
            }


            return RedirectToAction(nameof(Login));
        }

        /// <summary>
        /// 跳转到用户修改个人信息的页面
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Edit()
        {
            var editVm = new EditViewModel();
            return View(editVm);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(EditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model); //未添加model
            }

            var edit1 = new User
            {
                Id= Convert.ToInt32(User.Claims.LastOrDefault(u => u.Type == "Id")?.Value),
                Name = model.Name,
                Email = model.Email,
                Phone = model.PhoneNum,
            };

            try
            {
                await _accountService.UserChangeInfo(edit1);
                //throw new NotImplementedException("完成用户信息修改逻辑");
            }
            catch (EmailExistException)
            {
                ModelState.AddModelError("", "邮箱已经存在!");
            }

            return RedirectToAction(nameof(Index), "Home");
        }

        /// <summary>
        /// 用于添加收货地址
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult AddAddress()
        {
            var addAddress = new AddAddressModel();
            return View(addAddress);
        }

        /// <summary>
        ///添加收货地址
        /// </summary>
        /// <param name="model"></param>
        /// <returns>默认跳转到登录页面</returns>
        [HttpPost]
        public async Task<IActionResult> AddAddress(AddAddressModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var reg = new ContactInfo
            {
                Address = model.MainAddress,
                Name = model.UserName,
                Phone = model.UserTelephone
            };

            await _accountService.UserAddContact(Convert.ToInt32(User.Claims.LastOrDefault(u => u.Type == "Id")?.Value),
                reg);
            return RedirectToAction(nameof(AddAddress), "User");
        }

        [Authorize]
        public async Task<RedirectToActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            return RedirectToAction(nameof(Login));
        }
        
    }
}